from flask import Blueprint, jsonify, session
from easyRead.extensions import db
from flask import request, make_response
from werkzeug.security import check_password_hash, generate_password_hash
from forms import LoginForm
from forms import PasswordForm
from easyRead.models import User



bp = Blueprint("login", __name__, url_prefix="/users")

@bp.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return make_response(jsonify("用户请求登录，跳转至登录页面！"))
    else:
        form = LoginForm(request.form)
        if form.validate():
            id = form.id.data
            password = form.password.data
            user = User.query.filter_by(id=id).first()
            if not user:
                return make_response(jsonify("学工号在数据库中不存在！"))
            if check_password_hash(user.password, password):
                session['user'] = user
                return make_response("用户登录成功！")
                # return json.dumps({"code": 200, "message": "用户登录成功！", "data": None})
            else:
                return make_response(jsonify("学工号或密码错误！"))
        else:
            return make_response(jsonify(form.errors))
@bp.route("/logout")
def logout():
    session.clear()
    return make_response(jsonify("用户退出登录，跳转至主页面！"))

# 用户忘记密码后进行修改
@bp.route("/password", methods=['POST'])
def password():
    form = PasswordForm(request.form)
    if form.validate():
        email = form.email.data
        password = form.password.data
        user = User.query.filter_by(email=email).first()
        user.password = generate_password_hash(password)
        db.session.commit()
        return make_response(jsonify("修改密码成功！跳转至登录界面"))
    else:
        return make_response(jsonify(form.errors))